package com.zsj.juc.lock;


import java.util.concurrent.TimeUnit;

/**
 * @author zsj
 * @version 1.0
 * @date 2024/4/19 21:03
 * @description 死锁
 */
public class DeathLockDemo {

    /**
     * 以下就是经典的死锁代码
     * a线程持有a锁 想去获得b锁
     * 而b锁被b线程持有 b线程需要获得了a锁才能释放b锁
     *
     * 如何检测死锁;
     * 命令行: jps -l  jstack 进程编号
     * 图形化: jconsole
     */
    public static void main(String[] args) {
        final Object a = new Object();

        final Object b = new Object();

        new Thread(() -> {
            synchronized (a) {
                System.out.println(Thread.currentThread().getName() + "持有a锁,想去获取b锁");
                try {
                    TimeUnit.MILLISECONDS.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (b) {
                    System.out.println(Thread.currentThread().getName() + "获得了b锁");
                }
            }

        }, "a").start();

        new Thread(() -> {
            synchronized (b) {
                System.out.println(Thread.currentThread().getName() + "持有b锁,想去获取a锁");
                try {
                    TimeUnit.MILLISECONDS.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (a) {
                    System.out.println(Thread.currentThread().getName() + "获得了a锁");
                }
            }
        }, "b").start();


    }
}
